<template>
    <div class="test-component-page">
        <template v-if="Object.keys(fieldConfig).length">
            <t class="t2">{{ fieldConfig.name || '' }}</t>
            <p>
                <span v-if="fieldConfig.des">{{ fieldConfig.des }}；</span>
                <span v-if="fieldConfig.valueType">
                    该控件<span class="s-code">v-model</span>绑定的值类型为:<span class="d-code">{{ fieldConfig.valueType }}</span>
                </span>
            </p>
        </template>
        <t class="t2" v-else>使用示例</t>
        <component v-for="(comp, key) in components" :key="key" :is="comp"></component>
        <template v-for="(data, key) in configTableDatas">
            <config-table v-if="data.length" :key="key" :title="titles[key]" :step="key" :table-data="data"></config-table>
        </template>

        <el-backtop target=".main-container"></el-backtop>
    </div>
</template>

<script>
import {
    onMounted, computed, watch, nextTick,
} from 'vue';
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';
import fieldTypes from '../utils/field-types-desc';

export default {
    setup() {
        const route = useRoute();
        const store = useStore();
        const components = computed(() => {
            const comps = {};
            Array(20).fill().forEach((_, i) => {
                const example = `example${i + 1}`;
                let comp;
                // eslint-disable-next-line
                try { comp = require(`.${route.path}/${example}`).default; } catch (error) {}
                if (comp) comps[example] = comp;
            });
            return comps;
        });
        const configTableDatas = computed(() => {
            let datas = {};
            // eslint-disable-next-line
            try { datas = require(`.${route.path}/attributes`).default; } catch (error) {}
            return datas;
        });
        const fieldConfig = computed(() => fieldTypes.find(({ path, code }) => (path || `/${code}`) === route.path) || {});
        const titles = computed(() => {
            const compName = (route.path || '').slice(1).split('-').map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join('');
            return {
                attributes: `${compName} 属性`,
                events: `${compName} 事件`,
                slots: `${compName} 插槽`,
                refs: `${compName} 方法`,
            };
        });

        watch(route, () => {
            nextTick(() => { store.commit('updateArticleTree'); });
        });
        onMounted(() => { store.commit('updateArticleTree'); });

        return {
            components, fieldConfig, configTableDatas, titles,
        };
    },
};
</script>
